// pages/yuding/order/order.js
let app = getApp();
import {
  calcuFres
} from "../../../config/CalculationFreight.js";

import { tmplIds } from "../../../config/tmplIds.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},

    addressInfo: {},
    carType: [{
      name: "BigCar",
      value: "大车（13-15方）",
      checked: 'true'
    }, {
      name: "minCar",
      value: "小车（6-10方）"
    }],
    carts: {}, //购物车
    distance: 0, //配送距离
    chooseCarType: "大车（13-15方）",
    amount: 0, //货物总方数
    deliveryTime: "",
    deliverCost: 0,
    goodsPrice: 0,
    totalPrice: 0,
    note: "",
    distributionPoint: "",
  },
  notePut(e) {
    this.setData({
      note: e.detail.value,
    });
  },
  submitOrder: function(e) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '是否提交订单？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.baseUrl + "/orders/insert",
            method: "POST",
            header: {
              "cookie": "JESSIONID=" + that.data.userInfo.sessionId,
            },
            data: {
              buildingNature: that.data.addressInfo.buildingNature, //楼房性质
              contactName: that.data.addressInfo.contactName, //联系人姓名
              contactPhone: that.data.addressInfo.contactPhone, //联系人电话
              deliveryAddress: that.data.addressInfo.address, //配送地址
              deliveryTime: that.data.deliveryTime, //配送时间
              extendGoods: that.data.extendGoods, //商品集合和购买数量
              propertyNature: that.data.addressInfo.propertyNature, //楼盘性质
              userId: that.data.userInfo.userId, //用户id
              remark: that.data.note, //订单说明
              protocolUrl: wx.getStorageSync("serverFilePath"), //协议图片地址
              distance: that.data.distance, //配送距离
              carType: that.data.chooseCarType, //配送车型
              carriage: that.data.deliverCost, //运费
              totalAmount: that.data.totalPrice, //总价格
              distributionPoint: that.data.distributionPoint //配送点
            },
            success(res) {
              console.log(res);
              if (res.data.code == 1) {
                wx.showToast({
                  title: '预约中',
                  icon: "success",
                  duration: 2000,
                  success() {
                    wx.removeStorageSync("deliveryTime");
                    wx.removeStorageSync("addressInfo");
                    wx.removeStorageSync("dis");
                    wx.removeStorageSync("distributionPoint");
                    wx.removeStorageSync("serverFilePath");
                    wx.removeStorageSync("carts");
                  }
                });
              } else {
                wx.showToast({
                  title: '服务器异常！',
                  icon: "none",
                  duration: 2000,
                });
              }
            },
            fail(err) {
              wx.showToast({
                title: '服务器异常！',
                icon: "none",
                duration: 2000,
              });
            },
            complete() {
              wx.requestSubscribeMessage({
                tmplIds: tmplIds,
                
                success(res) {
                      wx.switchTab({
                        url: "/pages/dingdan/dingdan",
                      });
                  console.log("requestSubscribeMessageRes", res);
                },
                fail(err) {
                  wx.showModal({
                    title: '警告',
                    content: '您已拒绝接收微信服务通知,请保持手机通畅',
                    showCancel: false
                  });
                  console.log("requestSubscribeMessageErr", err);
                },
              });
            }
          })
        } else if (res.cancel) {
          return;
        }
      }
    });

  },
  radioChange: function(e) {
    let _this = this;
    let goodsPrice = Number(_this.data.goodsPrice);
    let deliverCost = calcuFres(e.detail.value, _this.data.distance, _this.data.amount);
    _this.setData({
      deliverCost: Number(deliverCost),
      totalPrice: (Number(deliverCost) + goodsPrice).toFixed(2),
      chooseCarType: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    let extendGoods = [];
    let deliverCost = 0;
    let goodsPrice = 0;
    let totalPrice = 0;
    let amount = 0;
    let dis = wx.getStorageSync("dis");
    let carts = wx.getStorageSync("carts");
    carts.forEach((val, index) => {
      //货物格式化
      let f_goods = {
        goods: {
          id: "",
        },
      };
      f_goods.goods.id = val.id;
      extendGoods.push(f_goods);
      extendGoods[index].num = val.num;
      //算货物费用
      goodsPrice += val.num * val.salePrice;
      //算货物总方数
      if (val.unit == "一方") {
        amount += val.num;
      } else if (val.unit == "半方") {
        amount += val.num / 2;
      }
    });
    //调用函数计算运费
    deliverCost = calcuFres("大车（13-15方）", dis, amount);
    that.setData({
      userInfo: wx.getStorageSync("userInfo"),
      addressInfo: wx.getStorageSync("addressInfo"),
      deliveryTime: wx.getStorageSync("deliveryTime"),
      carts: wx.getStorageSync("carts"),
      distributionPoint: wx.getStorageSync("distributionPoint"),
      extendGoods: extendGoods,
      amount: amount,
      goodsPrice: Number(goodsPrice),
      deliverCost: Number(deliverCost),
      totalPrice: (Number(goodsPrice) + Number(deliverCost)).toFixed(2),
      distance: dis,
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})